import api from '../../config/setting.js'
Page({
  data: {
    userInfo: {
      userName: 'admin',
      password: '',
      verificationCode: '',
      uuid: ''
    },
    captcha: '',
  },
  onLoad() {
    this.getVierificationCode()
  },
  getVierificationCode() {
    wx.request({
      url: api.verfCode,
      method: 'GET',
      success: (res) => {
        console.log(res)
        this.setData({
          captcha: 'data:image/png;base64,' + res.data.img,
          'userInfo.uuid': res.data.uuid
          //userInfo.UUID = x.uuid;
        })
      }
    })
  },
  onUsernameInput(e) {
    this.setData({
      'userInfo.userName': e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      'userInfo.password': e.detail.value
    });
  },

  onCaptchaInput(e) {
    this.setData({
      'userInfo.verificationCode': e.detail.value
    });
  },
  //刷新验证码
  refreshCaptcha() {
    // 刷新验证码逻辑，可以替换为实际的验证码图片请求
    this.getVierificationCode()
    console.log('刷新验证码');
  },

  onLogin() {
    const { userName, password, verificationCode, uuid } = this.data.userInfo;
    if (!userName || !password || !verificationCode) {
      wx.showToast({
        title: '请输入完整信息',
        icon: 'none'
      });
      return;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    // 登录逻辑，可以替换为实际的 API 请求
    wx.request({
      url: api.login,
      method: 'POST',
      data: this.data.userInfo,
      success: (res) => {
        console.log('请求成功', res.data);
        if (res.data.status) {
          // 登录成功，处理返回的数据
          let tmpUser = res.data; // 直接使用 res.data
          console.log('登录成功，用户信息：', tmpUser);
          // 保存用户信息到本地存储
          wx.setStorageSync('userInfo', tmpUser.data);
          this.setData({
            loginUser: tmpUser.data
          })
          wx.showToast({
            title: '登录成功，即将跳转。',
            icon: 'success',
            duration: 2000,
            complete: () => {
              wx.switchTab({
                url: '/pages/index/index'
              });
            }
          });
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败', err);
        wx.showToast({
          title: '网络请求失败，请检查网络',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  }
});